<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
		
		<!-- 咖啡机控制界面 -->
		<view class="coffee-machine">
			<view class="machine-status">
				<text class="status-text">咖啡机状态: {{machineStatus}}</text>
				<text class="connection-text" :class="isConnected ? 'connected' : 'disconnected'">
					{{isConnected ? '已连接' : '未连接'}}
				</text>
			</view>
			
			<!-- 设备扫描和连接 -->
			<view class="device-section" v-if="!isConnected">
				<button @click="scanDevices" :disabled="scanning" class="action-btn">
					{{scanning ? '正在扫描...' : '扫描设备'}}
				</button>
				
				<view class="device-list" v-if="devices.length > 0">
					<text class="section-title">可用设备</text>
					<view 
						v-for="(device, index) in devices" 
						:key="index" 
						class="device-item"
						:class="{ selected: selectedDevice === device.id }"
						@click="selectDevice(device.id)">
						<text class="device-name">{{device.name}} ({{device.id}})</text>
						<text class="device-rssi">信号: {{device.rssi}}dBm</text>
					</view>
					
					<button @click="connectMachine" :disabled="!selectedDevice" class="connect-btn">连接设备</button>
				</view>
			</view>
			
			<!-- 已连接时的控制面板 -->
			<view class="machine-control" v-if="isConnected">
				<button @click="disconnectMachine" class="action-btn disconnect-btn">断开连接</button>
				
				<!-- 咖啡机信息 -->
				<view class="machine-info" v-if="machineInfo">
					<text class="section-title">咖啡机状态</text>
					<view class="info-grid">
						<view class="info-item">
							<text class="info-label">水位</text>
							<progress :percent="machineInfo.waterLevel" stroke-width="4" />
							<text class="info-value">{{machineInfo.waterLevel}}%</text>
						</view>
						<view class="info-item">
							<text class="info-label">豆量</text>
							<progress :percent="machineInfo.beanLevel" stroke-width="4" />
							<text class="info-value">{{machineInfo.beanLevel}}%</text>
						</view>
						<view class="info-item">
							<text class="info-label">温度</text>
							<text class="info-value">{{machineInfo.temperature}}℃</text>
						</view>
						<view class="info-item" v-if="machineInfo.error">
							<text class="info-label error-text">错误</text>
							<text class="info-value error-text">{{machineInfo.error}}</text>
						</view>
					</view>
				</view>
				
				<!-- 制作进度 -->
				<view class="brewing-progress" v-if="brewing">
					<text class="section-title">制作进度</text>
					<progress :percent="brewingProgress.progress" stroke-width="4" :activeColor="'#795548'" />
					<view class="progress-info">
						<text>{{brewingProgress.progress}}%</text>
						<text v-if="brewingProgress.remaining > 0">剩余: {{brewingProgress.remaining}}秒</text>
						<text>状态: {{brewingStatusText}}</text>
					</view>
				</view>
				
				<!-- 咖啡选择 -->
				<view class="coffee-types">
					<text class="section-title">选择咖啡类型</text>
					<view class="coffee-grid">
						<view 
							v-for="(coffee, index) in coffeeTypes" 
							:key="index" 
							class="coffee-item"
							:class="{ selected: selectedCoffee === coffee.id }"
							@click="selectCoffee(coffee.id)">
							<text class="coffee-name">{{coffee.name}}</text>
						</view>
					</view>
				</view>
				
				<!-- 咖啡选项 -->
				<view class="coffee-options" v-if="selectedCoffee">
					<text class="section-title">咖啡选项</text>
					<view class="option-row">
						<text>温度</text>
						<slider :value="temperature" @change="temperatureChange" min="60" max="95" step="1" show-value />
						<text class="option-value">{{temperature}}℃</text>
					</view>
					<view class="option-row">
						<text>浓度</text>
						<slider :value="strength" @change="strengthChange" min="1" max="5" step="1" show-value />
						<text class="option-value">{{strength}}</text>
					</view>
					<view class="option-row">
						<text>水量</text>
						<slider :value="waterAmount" @change="waterAmountChange" min="30" max="250" step="5" show-value />
						<text class="option-value">{{waterAmount}}ml</text>
					</view>
				</view>
				
				<!-- 冲泡控制 -->
				<view class="brew-actions" v-if="selectedCoffee">
					<button @click="brewCoffee" class="brew-btn" :disabled="brewing">
						{{brewing ? '正在制作...' : '制作咖啡'}}
					</button>
					<button @click="stopBrewing" class="stop-btn" :disabled="!brewing">
						停止
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import coffeeService from '../../utils/coffeeService.js';
	
	export default {
		data() {
			return {
				title: '咖啡控制中心',
				isConnected: false,
				machineStatus: '待机中',
				brewing: false,
				selectedCoffee: null,
				temperature: 85,
				strength: 3,
				waterAmount: 120,
				coffeeTypes: [
					{ id: 1, name: '浓缩咖啡' },
					{ id: 2, name: '美式咖啡' },
					{ id: 3, name: '拿铁' },
					{ id: 4, name: '卡布奇诺' },
					{ id: 5, name: '摩卡' },
					{ id: 6, name: '热水' },
				],
				devices: [],
				selectedDevice: null,
				scanning: false,
				machineInfo: null,
				brewingProgress: {
					progress: 0,
					status: 'idle', // 'idle', 'brewing', 'finished', 'error'
					remaining: 0
				},
				// 进度检查计时器
				progressTimer: null
			}
		},
		computed: {
			// 格式化状态文本
			brewingStatusText() {
				const statusMap = {
					'idle': '待机',
					'brewing': '制作中',
					'finished': '已完成',
					'error': '出错'
				};
				return statusMap[this.brewingProgress.status] || '未知';
			}
		},
		onLoad() {
			// 初始化咖啡机SDK
			this.initCoffeeMachine();
		},
		onUnload() {
			// 页面卸载时清理资源
			this.clearProgressTimer();
			if (this.isConnected) {
				this.disconnectMachine();
			}
		},
		methods: {
			// 初始化咖啡机SDK
			async initCoffeeMachine() {
				try {
					await coffeeService.init();
					console.log('咖啡机SDK初始化成功');
				} catch (error) {
					console.error('咖啡机SDK初始化失败:', error);
					uni.showToast({
						title: '咖啡机SDK初始化失败',
						icon: 'none'
					});
				}
			},
			
			// 搜索咖啡机设备
			async scanDevices() {
				this.scanning = true;
				this.devices = [];
				this.machineStatus = '正在搜索设备...';
				
				try {
					const devices = await coffeeService.scanDevices();
					this.devices = devices;
					this.machineStatus = '搜索完成，请选择设备';
					
					if (devices.length > 0) {
						this.selectedDevice = devices[0].id;
					}
				} catch (error) {
					console.error('搜索设备失败:', error);
					uni.showToast({
						title: '搜索设备失败',
						icon: 'none'
					});
					this.machineStatus = '搜索设备失败';
				} finally {
					this.scanning = false;
				}
			},
			
			// 连接咖啡机
			async connectMachine() {
				if (!this.selectedDevice) {
					uni.showToast({
						title: '请先选择设备',
						icon: 'none'
					});
					return;
				}
				
				this.machineStatus = '正在连接...';
				
				try {
					const result = await coffeeService.connect(this.selectedDevice);
					if (result) {
						this.isConnected = true;
						this.machineStatus = '就绪';
						uni.showToast({
							title: '咖啡机连接成功',
							icon: 'success'
						});
						
						// 添加状态变化监听
						this.setupListeners();
						
						// 获取咖啡机状态
						this.getMachineStatus();
					} else {
						this.machineStatus = '连接失败';
						uni.showToast({
							title: '咖啡机连接失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('连接设备失败:', error);
					this.machineStatus = '连接失败';
					uni.showToast({
						title: '连接设备失败',
						icon: 'none'
					});
				}
			},
			
			// 设置事件监听器
			setupListeners() {
				// 添加状态变化监听
				coffeeService.addStatusChangeListener((status) => {
					console.log('状态更新:', status);
					this.machineInfo = status;
					
					// 如果有错误，更新机器状态
					if (status.error) {
						this.machineStatus = `错误: ${status.error}`;
					}
				});
				
				// 添加连接状态监听
				coffeeService.addConnectionChangeListener((connected) => {
					console.log('连接状态变化:', connected);
					this.isConnected = connected;
					if (!connected) {
						this.machineStatus = '已断开连接';
						this.machineInfo = null;
						this.clearProgressTimer();
					}
				});
			},
			
			// 移除事件监听器
			removeListeners() {
				coffeeService.removeStatusChangeListener();
				coffeeService.removeConnectionChangeListener();
				coffeeService.removeBrewingProgressListener();
			},
			
			// 获取咖啡机状态
			async getMachineStatus() {
				if (!this.isConnected) return;
				
				try {
					const status = await coffeeService.getStatus();
					this.machineInfo = status;
				} catch (error) {
					console.error('获取设备状态失败:', error);
				}
			},
			
			// 断开咖啡机连接
			async disconnectMachine() {
				// 如果正在制作咖啡，先停止
				if (this.brewing) {
					await this.stopBrewing();
				}
				
				this.machineStatus = '正在断开连接...';
				
				// 移除监听器
				this.removeListeners();
				this.clearProgressTimer();
				
				try {
					const result = await coffeeService.disconnect();
					if (result) {
						this.isConnected = false;
						this.machineStatus = '已断开连接';
						this.selectedCoffee = null;
						this.machineInfo = null;
						uni.showToast({
							title: '咖啡机已断开连接',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('断开连接失败:', error);
					uni.showToast({
						title: '断开连接失败',
						icon: 'none'
					});
				}
			},
			
			// 开始进度检查定时器
			startProgressTimer() {
				this.clearProgressTimer();
				
				this.progressTimer = setInterval(async () => {
					try {
						const progress = await coffeeService.getBrewingProgress();
						this.brewingProgress = progress;
						
						// 如果状态是已完成或错误，停止定时器
						if (progress.status === 'finished' || progress.status === 'error') {
							this.brewing = false;
							this.clearProgressTimer();
							
							// 更新机器状态
							if (progress.status === 'finished') {
								this.machineStatus = '就绪';
								uni.showToast({
									title: '咖啡制作完成！',
									icon: 'success'
								});
							} else {
								this.machineStatus = '制作出错';
								uni.showToast({
									title: '咖啡制作出错',
									icon: 'none'
								});
							}
							
							uni.hideLoading();
						}
					} catch (error) {
						console.error('获取进度失败:', error);
					}
				}, 1000);
			},
			
			// 清除进度检查定时器
			clearProgressTimer() {
				if (this.progressTimer) {
					clearInterval(this.progressTimer);
					this.progressTimer = null;
				}
			},
			
			// 选择设备
			selectDevice(deviceId) {
				this.selectedDevice = deviceId;
			},
			
			// 选择咖啡类型
			selectCoffee(coffeeId) {
				this.selectedCoffee = coffeeId;
				// 根据咖啡类型设置默认参数
				switch(coffeeId) {
					case 1: // 浓缩咖啡
						this.temperature = 90;
						this.strength = 5;
						this.waterAmount = 40;
						break;
					case 2: // 美式咖啡
						this.temperature = 85;
						this.strength = 3;
						this.waterAmount = 150;
						break;
					case 3: // 拿铁
						this.temperature = 80;
						this.strength = 4;
						this.waterAmount = 120;
						break;
					case 4: // 卡布奇诺
						this.temperature = 85;
						this.strength = 4;
						this.waterAmount = 120;
						break;
					case 5: // 摩卡
						this.temperature = 85;
						this.strength = 4;
						this.waterAmount = 120;
						break;
					case 6: // 热水
						this.temperature = 95;
						this.strength = 0;
						this.waterAmount = 200;
						break;
				}
			},
			
			// 温度调节
			temperatureChange(e) {
				this.temperature = e.detail.value;
			},
			
			// 浓度调节
			strengthChange(e) {
				this.strength = e.detail.value;
			},
			
			// 水量调节
			waterAmountChange(e) {
				this.waterAmount = e.detail.value;
			},
			
			// 制作咖啡
			async brewCoffee() {
				if (!this.selectedCoffee) {
					uni.showToast({
						title: '请选择咖啡类型',
						icon: 'none'
					});
					return;
				}
				
				this.brewing = true;
				this.machineStatus = '正在制作咖啡...';
				this.brewingProgress = {
					progress: 0,
					status: 'brewing',
					remaining: 100
				};
				
				const coffee = this.coffeeTypes.find(item => item.id === this.selectedCoffee);
				
				uni.showLoading({
					title: `正在制作${coffee.name}...`
				});
				
				// 启动进度检查
				this.startProgressTimer();
				
				try {
					// 调用SDK制作咖啡
					const result = await coffeeService.brewCoffee({
						type: this.selectedCoffee,
						temperature: this.temperature,
						strength: this.strength,
						waterAmount: this.waterAmount
					});
					
					if (result.success) {
						// 不在这里停止brewing和计时器，而是在进度检查中完成
						// this.brewing = false; 
						// this.machineStatus = '就绪';
						// uni.hideLoading();
						// uni.showToast({
						//     title: `${coffee.name}制作完成！`,
						//     icon: 'success'
						// });
					} else {
						throw new Error('制作失败');
					}
				} catch (error) {
					console.error('制作咖啡失败:', error);
					this.brewing = false;
					this.machineStatus = '制作失败';
					this.clearProgressTimer();
					uni.hideLoading();
					uni.showToast({
						title: '制作咖啡失败',
						icon: 'none'
					});
				}
			},
			
			// 停止制作
			async stopBrewing() {
				if (this.brewing) {
					this.clearProgressTimer();
					
					try {
						const result = await coffeeService.stopBrewing();
						if (result) {
							this.brewing = false;
							this.machineStatus = '就绪';
							uni.hideLoading();
							uni.showToast({
								title: '已停止制作',
								icon: 'none'
							});
						}
					} catch (error) {
						console.error('停止制作失败:', error);
						uni.showToast({
							title: '停止制作失败',
							icon: 'none'
						});
					}
				}
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 20rpx;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 100rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 30rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
		margin-bottom: 40rpx;
	}

	.title {
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
	}
	
	/* 咖啡机样式 */
	.coffee-machine {
		width: 100%;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}
	
	.machine-status {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
		padding: 15rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.05);
	}
	
	.status-text {
		font-size: 28rpx;
	}
	
	.connection-text {
		font-size: 28rpx;
		font-weight: bold;
	}
	
	.connected {
		color: #4CAF50;
	}
	
	.disconnected {
		color: #F44336;
	}
	
	.device-section {
		margin-bottom: 30rpx;
	}
	
	.action-btn {
		background-color: #2196F3;
		color: white;
		margin-bottom: 20rpx;
		font-size: 28rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		margin: 20rpx 0;
		color: #333;
	}
	
	.device-list {
		margin-bottom: 30rpx;
	}
	
	.device-item {
		padding: 20rpx;
		margin: 20rpx 0;
		background-color: #fff;
		border-radius: 10rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.1);
	}
	
	.selected {
		background-color: #FFC107;
	}
	
	.selected .device-name, .selected .device-rssi {
		color: #fff;
	}
	
	.device-name {
		font-size: 28rpx;
		color: #333;
		flex: 2;
	}
	
	.device-rssi {
		font-size: 24rpx;
		color: #666;
		flex: 1;
		text-align: right;
	}
	
	.connect-btn {
		background-color: #4CAF50;
		color: white;
		margin-top: 20rpx;
	}
	
	.machine-control {
		display: flex;
		flex-direction: column;
	}
	
	.machine-info {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.1);
	}
	
	.info-grid {
		display: flex;
		justify-content: space-between;
		margin: 20rpx 0;
		flex-wrap: wrap;
	}
	
	.info-item {
		width: 45%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20rpx;
	}
	
	.info-label {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
	
	.error-text {
		color: #F44336;
	}
	
	.info-value {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-top: 10rpx;
	}
	
	/* 制作进度样式 */
	.brewing-progress {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.1);
	}
	
	.progress-info {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
	}
	
	.progress-info text {
		font-size: 28rpx;
		color: #333;
	}
	
	.coffee-types {
		margin-bottom: 30rpx;
	}
	
	.coffee-grid {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 30rpx;
	}
	
	.coffee-item {
		width: 30%;
		height: 120rpx;
		margin: 1.5%;
		background-color: #fff;
		border-radius: 10rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.1);
		transition: all 0.3s ease;
	}
	
	.coffee-item.selected {
		background-color: #795548;
		transform: scale(1.05);
	}
	
	.selected .coffee-name {
		color: #fff;
	}
	
	.coffee-name {
		font-size: 28rpx;
		color: #333;
	}
	
	.coffee-options {
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.1);
	}
	
	.option-row {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
	}
	
	.option-row text {
		width: 100rpx;
		font-size: 28rpx;
		color: #666;
	}
	
	.option-row slider {
		flex: 1;
	}
	
	.option-value {
		width: 80rpx;
		text-align: right;
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}
	
	.brew-actions {
		display: flex;
		margin-top: 30rpx;
	}
	
	.brew-btn {
		flex: 2;
		background-color: #795548;
		color: white;
		font-size: 32rpx;
		height: 100rpx;
		line-height: 100rpx;
	}
	
	.brew-btn[disabled] {
		background-color: #BDBDBD;
		color: #757575;
	}
	
	.stop-btn {
		flex: 1;
		background-color: #F44336;
		color: white;
		margin-left: 20rpx;
	}
	
	.stop-btn[disabled] {
		background-color: #BDBDBD;
		color: #757575;
	}
	
	.disconnect-btn {
		background-color: #F44336;
		color: white;
		margin-bottom: 20rpx;
	}
</style>

